import React, { useState, useEffect } from 'react'
import { connect } from 'react-redux'
import { getElementActivePageTreeSelector } from '../../selectors/baseSelector'
import { Treebeard } from 'react-treebeard'
import treeStyleObject from './elementTreeStyle'
import { genElementSetActiveNode } from '../../actions/home'
import { ColHeader } from '../common/colHeader'

const maStateToProps = state => {
    return {
        tree: getElementActivePageTreeSelector(state)
    }
}

const mapDispatchToProps = dispatch => {
    return {
        setActiveNode: node => dispatch(genElementSetActiveNode(node))
    }
}

export const ElementTree = connect(maStateToProps, mapDispatchToProps)((props) => {
    const { setActiveNode, tree } = props
    const [cursor, setCursor] = useState(null)
    const [data, setData] = useState(tree)

    const findNode = (parentNode, ifMatch) => {
        if (ifMatch(parentNode)) {
            return parentNode
        }

        const children = parentNode.children || []
        for (let i = 0; i < children.length; i++) {
            const matched = findNode(children[i], ifMatch)
            if (matched) {
                return matched
            }
        }

        return null
    }

    useEffect(() => {
        const activeNode = findNode(tree, node => node.active)
        activeNode && delete activeNode.active

        setCursor({ ...tree, active: true })
        setData({ ...tree, active: true })
    }, [tree])

    const onToggle = (node, toggled) => {
        if (cursor) {
            const matchedNode = findNode(data, node => node.name === cursor.name)
            if (matchedNode) {
                matchedNode.active = false
                if (matchedNode.children) {
                    matchedNode.toggled = toggled
                }
            }
        }

        if (node.children && node.active) {
            node.toggled = toggled
        }
        node.active = true

        setCursor(node)
        setData(Object.assign({}, data))
        setActiveNode(node)
    }

    return (
        <React.Fragment>
            <ColHeader title='所选页面元素树结构：' />
            <Treebeard
                data={data}
                onToggle={onToggle}
                style={treeStyleObject}
            />
        </React.Fragment>
    )
})